package Web;


import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import DB.ConnectToDB;

/**
 * Servlet implementation class Login
 */
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
		return;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		PreparedStatement stmt = null;
		Connection con = null;
		ResultSet res = null;
		
		String user = request.getParameter("username");
		String pass = request.getParameter("password");	
		
		//Check input
		if (null == pass || null == user || pass.length() > 8 || user.length() > 8){
			response.sendError(HttpServletResponse.SC_BAD_REQUEST);
			return;
			
		}
	
		try {	
			Properties p = new Properties();
			p.load(getServletContext().getResourceAsStream("/WEB-INF/config"));
			con = (new ConnectToDB(p)).getConnection();
			 
			stmt = con.prepareStatement("SELECT * from user where username = ? And password = ?");
			stmt.setString(1, user);
			stmt.setString(2, pass);
			res = stmt.executeQuery(); 
			
			boolean resultFailed = (!res.next() || !res.getString("password").equals(pass));
	
			if (!resultFailed){
				request.getSession().setAttribute("username", user); 
				String admin = res.getBoolean("administrator") ? "true" : "false";
				request.getSession().setAttribute("administrator",admin);
				} 
			
			else {
				request.getSession().setAttribute("LastResultFailed", "true");
			}
			response.sendRedirect("index.jsp");
		
		}
		
		catch (Exception e) {
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			e.printStackTrace();} 
			
		finally { // Close the connection.
				if(res!=null){
				     try{res.close();}	catch(Exception e){e.printStackTrace();} }
				if(stmt !=null){
				     try{stmt.close();}	catch(Exception e){e.printStackTrace();} }
				if(con !=null){
				     try{con.close();}	catch(Exception e){e.printStackTrace();} }
				}
	}
		
}

